import pandas as pd
import os

def csv_to_xlsx(csv_file_path, xlsx_file_path=None):
    """
    将CSV文件转换为XLSX文件，确保所有数据以文本格式保存，使用C优化库提升速度
    
    参数:
    csv_file_path: CSV文件的路径
    xlsx_file_path: 输出XLSX文件的路径，默认为与CSV同路径同名称
    """

    if xlsx_file_path is None:
        file_name, _ = os.path.splitext(csv_file_path)
        xlsx_file_path = f"{file_name}.xlsx"
    
    try:
        # 读取CSV文件，将所有列都作为字符串处理
        df = pd.read_csv(csv_file_path, dtype=str, engine='c')
        
        with pd.ExcelWriter(xlsx_file_path, engine='xlsxwriter') as writer:
            # 获取xlsxwriter的工作簿和工作表对象
            workbook = writer.book
            worksheet = workbook.add_worksheet('Data')
            
            # 创建文本格式
            text_format = workbook.add_format({'num_format': '@'})
            
            # 写入表头
            for col_num, value in enumerate(df.columns.values):
                worksheet.write(0, col_num, value, text_format)
            
            # 写入数据，使用文本格式
            for row_num, row_data in enumerate(df.itertuples(index=False, name=None), start=1):
                for col_num, value in enumerate(row_data):
                    worksheet.write(row_num, col_num, value, text_format)
        
        print(f"转换完成！文件已保存至: {xlsx_file_path}")
        return True
    
    except Exception as e:
        print(f"转换失败: {str(e)}")
        return False

if __name__ == "__main__":
    csv_file = input("请输入CSV文件路径: ").strip('\'"')
    csv_to_xlsx(csv_file)
    os.system("pause")
